<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：100条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button
                type="warning"
                size="small"
                @click="$router.push('/import')"
                >导入excel</el-button
              >
              <el-button
                type="danger"
                size="small"
                :loading="downloadLoading"
                @click="exportData"
                >导出excel</el-button
              >
              <el-button
                v-if="canClick('p-em-add')"
                type="primary"
                size="small"
                @click="showDialog = true"
                >新增员工</el-button
              >
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table
            :default-sort="{ prop: 'workNumber', order: 'ascending' }"
            stripe
            border
            :data="employeeList"
          >
            <el-table-column type="index" label="序号" />
            <el-table-column prop="username" label="姓名" />
            <el-table-column prop="staffPhoto" label="头像">
              <template #default="{ row }">
                <el-image
                  :src="row.staffPhoto"
                  style="width: 80px; height: 80px; border-radius: 80px"
                  @click="showQRCodeDialog(row.staffPhoto)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column sortable prop="workNumber" label="工号" />
            <el-table-column prop="formOfEmployment" label="聘用形式">
              <template #default="{ row }">{{
                formatHireType(row.formOfEmployment)
              }}</template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column sortable prop="correctionTime" label="入职时间" />
            <el-table-column label="账户状态">
              <el-switch v-model="qy"></el-switch>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`/employees/detail/${row.id}`)"
                  >查看</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="openRoleDialog(row.id)"
                >
                  分配角色
                </el-button>
                <el-button type="text" size="small" @click="delEmployee(row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              :current-page="query.page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="query.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </el-row>
        </div>
      </el-card>
    </div>
    <AddEmployee
      :show-dialog="showDialog"
      @close-dialog="showDialog = $event"
    ></AddEmployee>

    <el-dialog title="分享二维码" :visible.sync="QRCodeDialog" width="width">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas"></canvas>
      </el-row>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <AssignRole
      ref="permission"
      :show-role-dialog.sync="showRoleDialog"
    ></AssignRole>
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/addEmployee.vue'
import AssignRole from './components/assign-role.vue'
import QRCode from 'qrcode'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data () {
    return {
      query: {
        page: 1,
        size: 5
      },
      total: 0,
      employeeList: [],
      qy: false,
      showDialog: false,
      downloadLoading: false,
      QRCodeDialog: false,
      showRoleDialog: false
    }
  },
  created () {
    this.getEmployeeList()
  },
  methods: {
    openRoleDialog (id) {
      this.showRoleDialog = true
      this.$refs.permission.getUserDetail(id)
    },
    showQRCodeDialog (url) {
      if (!url) return
      this.QRCodeDialog = true
      this.$nextTick(() => {
        QRCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    async getEmployeeList () {
      const { rows, total } = await getEmployeeListApi(this.query)
      this.employeeList = rows
      this.total = total
    },
    handleSizeChange (newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    },
    formatHireType (type) {
      const map = {}
      EmployeeEnum.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    async delEmployee (id) {
      try {
        await this.$confirm('确认删除该员工吗?')
        await delEmployeeApi(id)
        const newTotal = Math.ceil((this.total - 1) / this.query.size)
        if (newTotal < this.query.page) {
          this.query.page = newTotal
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
        this.$message.info('点击了取消')
      }
    },
    async exportData () {
      this.downloadLoading = true
      const userMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(userMap)
      const enHeader = Object.values(userMap)
      const data = this.transformList(this.employeeList, enHeader)
      const excel = await import('@/utils/Export2Excel')
      console.log(this.employeeList)
      console.log(excel)
      console.log(data)
      excel.export_json_to_excel({
        // 表头 必填
        // header: ['姓名', '工资'],
        header,
        // 表头对应的具体数据 必填
        // data: [
        //   ['刘备', 100],
        //   ['关羽', 500]
        // ],
        data,
        filename: 'excel-list', // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx' // 导出生成的文件类型
      })

      this.downloadLoading = false
    },
    transformList (list, enHeader) {
      const secondArray = []
      list.forEach(user => {
        const itemArray = []
        for (const key in user) {
          if (enHeader.includes(key)) {
            // 处理聘用关系=>转换数字
            if (key === 'formOfEmployment') {
              itemArray.push(this.formatHireType(user[key]))
            } else {
              itemArray.push(user[key])
            }
          }
        }
        secondArray.push(itemArray)
      })
      return secondArray
    }
  }
}
</script>
